<template>
  <div class="contentBox" style="position: relative">
    <div class="content" style="height: calc(100% - 88px)">
      <div class="content-top" style="height: calc(100% - 72px)">
        <div class="content-top-title">
          <div class="content-top-title-left">
            <div>
              <div class="content-top-title-left-name" style="margin-right: 48px">
                {{ form.name }}
              </div>
              <cusButton class="mr_20" style="height: 26px; font-size: 14px" type="primary"
                v-if="!isChange && !isLook" @onClick="changeNumBtn(1)">增加间餐夜餐</cusButton>
            </div>
            <div style="margin-right: 48px" v-if="!isLook && !form.meal_plan_id">
              <span>选择方式</span>
              <Select style="width: 150px" size="small" v-model="moshiType"
                @on-change="changeMoshi">
                <Option v-for="item in cityList" :value="item.value" :key="item.value">
                  {{ item.label }}
                </Option>
              </Select>
            </div>
            <div v-if="moshiType == 1">
              <span>常用食谱</span>
              <Select style="width: 150px" size="small" @on-change="changeChangui"
                v-model="changguiId">
                <Option v-for="item in changuiList" :value="item.mealPlanId" :key="item.mealPlanId">
                  {{ item.name }}
                </Option>
              </Select>
            </div>
            <div v-if="moshiType == 2">
              <span>配餐模式</span>
              <Select style="width: 150px" size="small" v-model="form.cateringModelId"
                @on-change="changePeican">
                <Option v-for="item in cateringList" :value="item.modeId" :key="item.modeId">
                  {{ item.modeName }}</Option>
              </Select>
            </div>
            <div v-if="moshiType == 3">
              <span>食谱模板</span>
              <Select style="width: 150px" size="small" @on-change="changeMuban">
                <Option v-for="item in mubanList" :value="item.mouldId" :key="item.mouldId">
                  {{ item.mouldName }}</Option>
              </Select>
            </div>
            <div v-if="moshiType == 4">
              <cusButton type="primary" @onClick="onImport()">食谱导入</cusButton>
            </div>
            <div class="content-top-title-left-name"
              style="color: rgb(24, 144, 255); cursor: pointer" @click="changeNumBtn"
              v-if="isChange">
              设置就餐人数
            </div>
          </div>
          <div class="content-top-title-right" v-if="!isLook">
            <span>拖拽模式</span>
            <Select style="width: 100px" size="small" placeholder="请选择模式" v-model="dragType"
              @on-change="changedragType">
              <Option v-for="item in copyMode" :value="item.value" :key="item.value">
                {{ item.label }}</Option>
            </Select>
          </div>
          <div class="content-top-title-right" v-if="isLook">
            <Button type="primary" ghost class="mr_10" @click="onExport(1)">食谱下料清单导出</Button>
            <Button type="primary" ghost class="mr_10" @click="onExport(2)">食谱公布表导出</Button>
            <Button type="primary" ghost @click="onExport(3)">食谱评估报告导出</Button>
          </div>
        </div>
        <div class="content-top-table" style="height: calc(100% - 81px)">
          <div class="addtable" style="height: 100%">
            <div class="addtable-title">
              <div class="addtable-title-title">餐食</div>
              <div class="addtable-title-item" v-for="(item, index) in dateList" :key="item">
                {{ dateStrList[index].name }}({{ item }})
              </div>
            </div>
            <div class="addtable-body" style="height: calc(100% - 51px)">
              <div class="addtable-body-hang" v-for="(item, key, index) in data" :key="index"
                :class="'hang' + (index % 3)">
                <div class="addtable-body-hang-title">
                  {{ key | mealTimeName(mealTimeList) }}
                </div>
                <div class="addtable-body-hang-content" v-for="(it, idx, num) in item.dayMeal"
                  :key="it.timeId">
                  <div class="peopleNum" style="margin:30px 0;color:gray"
                    v-if="!it.repastNumber && ['betwwenMealOne', 'betwwenMealTwo', 'midnightMealOne', 'midnightMealTwo'].includes(key)">
                    <div style="height: 202px;line-height: 202px;">无就餐人数暂不开餐</div>
                    <div style="margin:20px">
                      就餐人数：{{ it.repastNumber }} 人
                    </div>
                  </div>

                  <div style="padding: 5px" v-else>

                    <draggable v-model="item.dayMeal[idx].food" :group="groupItem"
                      dragClass="dragClass" :move="(e) => {
                        onMove(e, key, idx);
                      }
                      " @add="(e) => {
      onAdd(e, key, idx);
    }
    " @start="drag = true" @end="drag = false" :disabled="isLook">
                      <transition-group :style="{
                        minHeight: '200px',
                        display: 'block',
                        padding: '10px 10px 0',
                        border: '1px dashed gray',
                        borderRadius: '4px',
                      }">
                        <div v-for="(iAtem, iAdx) in item.dayMeal[idx].food" :key="iAtem.dishCode"
                          class="draggableItem" @mousedown="
                            wantTomove($event, index, idx, iAdx, iAtem)
                            ">
                          <div @click="
                            changeDishesBtn(key, idx, iAdx, iAtem.dishType)
                            " style="width: 60%">
                            <span :style="{
                              color: !iAtem.dishName
                                ? '#49AFFF'
                                : iAtem.duplicateFlag == 1
                                  ? '#fe3333'
                                  : iAtem.duplicateFlag == 2
                                    ? '#c5ba7b'
                                    : ''
                            }">{{ iAtem.dishName || "选择菜肴" }}</span>
                            <div>({{ iAtem.dishType }})</div>
                          </div>
                          <div v-if="wantTomoveItem.index == index &&
                            wantTomoveItem.key == idx &&
                            wantTomoveItem.aindex == iAdx &&
                            drag
                            " style="color: blue">
                            ({{
                              dragType == 1
                              ? "转移中"
                              : dragType == 2
                                ? "复制中"
                                : "替换下面菜肴"
                            }})
                          </div>
                          <div v-else style="width: 35%; text-align: right">
                            {{ iAtem.dishWeight || 0 }}克
                          </div>
                        </div>
                      </transition-group>
                    </draggable>
                    <div class="btnBox" v-if="!isLook">
                      <div @click="addBtn(key, idx, it.food)">
                        <Icon type="md-add" color="rgba(24, 144, 255, 1)" size="16" />
                        <span style="margin-left: 3px; color: rgba(24, 144, 255, 1)">新增</span>
                      </div>
                      <div style="margin: 0 10px" @click="
                        changeWeightBtn(key, idx, it.food, it.repastNumber)
                        " v-if="form.meal_plan_id">
                        <Icon type="ios-create" color="rgba(24, 144, 255, 1)" size="16" />
                        <span style="margin-left: 3px; color: rgba(24, 144, 255, 1)">详情</span>
                      </div>
                      <Poptip confirm title="是否确认删除此区间菜品数据?" @on-ok="onDelete(key, idx)">
                        <div v-if="form.meal_plan_id">
                          <Icon type="md-trash" color="red" size="16" />
                          <span style="margin-left: 3px; color: red">清空</span>
                        </div>
                      </Poptip>
                    </div>
                    <div class="peopleNum" :style="{ marginTop: isLook ? '10px' : '' }">
                      就餐人数：{{ it.repastNumber }} 人
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="content-bottom">
        <div class="content-top-title" style="height: 72px">
          <div class="content-top-title-left" @click="showNurBtn" style="cursor: pointer">
            <div class="content-top-title-left-name" style="margin-right: 48px">
              <span>查看食谱评估详情</span>
              <Icon type="ios-arrow-forward" size="20" />
            </div>
          </div>
          <div class="content-bottom-right">
            <span class="mr_10">平均伙食费</span>
            <Input style="width: 100px" readonly class="mr_16" :value="personMoney"></Input>
            <span class="mr_10">总金额</span>
            <Input style="width: 100px" readonly class="mr_16" :value="totalMoney"></Input>
            <cusButton type="primary" @onClick="openFenxi" ghost>营养分析</cusButton>
          </div>
        </div>
      </div>
    </div>
    <div class="cus_operBox" style="z-index: 1001; width: calc(100% - 250px)"
      :style="{zIndex:maskIndex}">
      <Button type="error" class="mr_20" @click="closeShowNutrition"
        v-if="showNutrition">返回</Button>
      <Button type="error" class="mr_20" @click="backTop" v-if="!showNutrition">返回</Button>
      <Button type="primary" class="mr_20" @click="overBtn" v-if="!showNutrition && !isLook"
        ghost>完成</Button>
      <Button type="primary" class="mr_20" @click="saveBtn"
        v-if="!showNutrition && !isLook">保存</Button>
    </div>
    <Spin size="large" fix v-if="loading" style="z-index: 4000">
      <div v-if="loadingA">
        <Icon type="ios-loading" size="38" class="demo-spin-icon-load"></Icon>
        <div style="margin-top: 10px">正在生成食谱...</div>
      </div>
    </Spin>

    <cus-uploadModal ref="cusUploadNutritionTagModal" titleName="导入食谱" :temp-src="exportRecipeExcel"
      :uploadFnc="uploadRecipeExcel" :width="700"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      @onError="onError" @onOk="oninit">
      <template #right>
        <Card class="draw-section-item">
          <!-- <div @click="intellectOk">1111</div> -->
          <cus-upload :uploadFnc="intellectImport" :autoUpload="true"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            @onOk="intellectOk" @onError="intellectError">
            <div class="draw-section-item-logo flex">
              <svg t="1628043694436" class="icon" viewBox="0 0 1157 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="24667" width="118" height="118">
                <path
                  d="M0.09216 582.528c0-124.37504 82.23744-233.71264 192.1536-266.112C253.07648 156.0832 403.70688 40.96 579.93216 40.96c177.64352 0 324.18304 115.07712 384.96768 275.456 113.4336 33.152 192.19968 141.06624 192.19968 266.112 0 153.96864-119.57248 279.14752-270.91968 279.14752-28.34432 0-53.92896-26.60864-53.92896-56.06912 0-33.8176 25.58464-56.1152 53.92896-56.1152 91.22816 0 163.80928-74.09664 163.80928-166.87616 0-49.61792-21.44768-95.67744-56.64768-125.1328l-9.66144-9.43616a48.96256 48.96256 0 0 0-12.46208-10.05568c-2.75968-3.60448-9.03168-3.60448-12.46208-6.49728h-3.42528c-2.75968-3.5584-6.23104-3.5584-9.0368-6.4512h-3.47136c-2.75968 0-6.23104-3.5584-9.65632-3.5584-2.75968 0-6.23104 0-6.23104-2.8928h-9.0368c-3.47136 0-6.23104 0-9.7024-3.60448h-25.4976c-2.75968-10.81344-6.23104-18.688-6.23104-29.50144-2.75968 0-2.75968-3.5584-2.75968-6.4512-3.42528-6.49728-3.42528-12.90752-6.23104-19.44576 0-3.5584-3.42528-3.5584-3.42528-7.16288-2.75968-6.49728-6.23104-12.90752-9.65632-19.4048v-6.49728c-2.80576-6.4512-9.07776-12.90752-12.46208-19.44576-53.18144-92.11392-151.38816-154.63936-261.97504-154.63936-113.34144 0-211.46624 62.5664-264.68864 154.63936l-9.0368 19.44576c0 2.18112-1.42336 2.18112-2.08896 4.31616l-1.3824 2.18112-9.7024 19.4048v7.16288l-8.94464 19.44576v6.4512c-3.47136 10.77248-6.94272 18.688-6.94272 29.46048h-28.30336c-2.75968 3.60448-6.23104 3.60448-8.94464 3.60448h-6.23104c-2.75968 2.18112-4.14208 2.8928-4.89472 2.8928a1.24928 1.24928 0 0 1-2.048 0c-2.75968 0-6.23104 3.5584-9.03168 3.5584h-6.23104c-3.42528 2.93376-6.23104 2.93376-9.65632 6.49728h-3.42528c-2.75968 2.8928-6.23104 2.8928-9.07776 6.49728h-3.42528c-2.75968 3.5584-6.23104 6.4512-9.7024 10.05568-6.23104 2.84672-8.94464 6.49728-12.416 9.39008-35.24608 29.50656-53.2224 75.56096-53.2224 125.17888 0 92.77952 72.58112 166.87616 160.37888 166.87616 32.4864 0 56.69376 22.29248 56.69376 56.06912 0 29.50656-24.20736 56.07424-56.69376 56.07424-147.82976 0.04096-270.8736-125.13792-270.8736-279.01952v-0.09216z"
                  p-id="24668"></path>
                <path
                  d="M362.94656 566.72768c0-16.54784 6.23104-28.78976 12.46208-39.56224l163.7632-186.90048c10.41408-10.81344 24.91904-16.55296 40.8064-16.55296 15.92832 0 28.34432 5.7856 41.47712 16.512l160.37888 186.98752c21.5296 22.19008 21.00224 57.63072-1.18784 79.16544a56.00256 56.00256 0 0 1-39.57248 15.80032c-15.92832 0-27.67872-8.6784-38.04672-19.45088l-69.10976-78.40768v281.9584c0 33.8176-24.21248 55.3984-53.93408 55.3984-31.104 0-53.2224-21.5808-53.2224-55.3984v-281.91232L457.69728 602.7264c-10.368 10.81344-25.54368 19.45088-41.43104 19.45088-28.3904 0-53.31456-25.90208-53.31456-55.40352v-0.04608z"
                  p-id="24669"></path>
              </svg>
            </div>
            <div class="draw-section-item-title">智能导入excel</div>
            <div class="draw-section-item-label">智能导入excel文件 <br /> 可拖拽上传</div>
          </cus-upload>
        </Card>
      </template>

    </cus-uploadModal>
    <!-- 菜肴信息匹配 -->
    <dishReview ref="dishReviewRef"></dishReview>
    <!-- 营养标签 -->
    <dishesTags ref="dishesTags"></dishesTags>
    <!-- 添加菜肴 -->
    <addDishes ref="addDishes" @onAdd="onAddBack"></addDishes>
    <!-- 替换菜肴 -->
    <changeOneDishes ref="changeOneDishes" @onAdd="onChangeBack"></changeOneDishes>
    <!-- 食谱营养评估详情 -->
    <nutritionModal ref="nutritionModal" :dataItem="nutritionData" :dateStrList="dateStrList"
      :dateList="dateList">
    </nutritionModal>
    <!-- 食谱营养评估 图表 -->
    <nutritionChart ref="nutritionChart" :dataItem="nutritionData" :dateStrList="dateStrList"
      :dateList="dateList">
    </nutritionChart>
    <!-- 选择常用模板 - 需要覆盖的数据 -->
    <chooseCoverData ref="chooseCoverData" :dateList="dateList" :dateStrList="dateStrList"
      @coverSuccess="coverSuccess">
    </chooseCoverData>
    <!-- 修改就餐人数 -->
    <changeNum ref="changeNum" :dateList="dateList" :dateStrList="dateStrList"
      @changerepastNumber="changerepastNumber" @filterMeal="filterMeal"></changeNum>
    <!-- 修改配餐重量占比 -->
    <changeWeight ref="changeWeight" @changeSettingSuccess="changeSettingSuccess"></changeWeight>
    <!-- 增加间餐夜餐 -->
    <chooseMealtimes ref="chooseMealtimes" @chooseMealsOk="chooseMealsOk"></chooseMealtimes>
  </div>
</template>
<script>
import {
	aptitudeCreateRecipe,
	saveMealPlan,
	uploadRecipeExcel,
	exportRecipeExcel,
	saveMealPlanTimesDish,
	unitStrength,
	getFoodBookById,
	cateringModeList,
	queryMealPlan,
	getMould,
	cateringModedtlList,
	mealPlanAssessmentStandard,
	mealPlanAssessment,
	realTimeCalculateMealPlanDishAssessment,
	downloadMealFoodTable,
	getFoodBookStatement,
	mealAssessmentReportExcel,
	mealReviewImport
} from '@/api/business/dishesModule'
import draggable from 'vuedraggable'
import addDishes from './components/addDishes'
import changeOneDishes from './components/changeOneDishes'
import nutritionModal from './components/nutritionModal'
import nutritionChart from './components/nutritionChart'
import chooseCoverData from './components/chooseCoverData'
import changeWeight from './components/changeWeight'
import changeNum from './components/changeNum'
import chooseMealtimes from './components/chooseMealtimes'
import dishesTags from '../orderDishesList/components/dishesTags'
import dishReview from './components/dishReview'
export default {
	components: {
		dishReview,
		dishesTags,
		draggable,
		addDishes,
		changeOneDishes,
		nutritionModal,
		nutritionChart,
		chooseCoverData,
		changeWeight,
		changeNum,
		chooseMealtimes
	},
	data() {
		return {
			intellectImport: mealReviewImport,
			uploadRecipeExcel: uploadRecipeExcel,
			exportRecipeExcel: exportRecipeExcel(),
			isLook: false, // 是否为查看状态
			isChange: false, // 是否为修改状态
			// 由于生成食谱时间过长，改变loading样式
			loadingA: false,
			nutritionData: {},
			// 判断接口请求数量
			interFaces: 0,
			showNutrition: false,
			form: {},
			loading: false,
			moshiType: null,
			cityList: [
				{
					label: '常用食谱',
					value: 1
				},
				{
					label: '配餐模式',
					value: 2
				},
				{
					label: '食谱模板',
					value: 3
				},
				{
					label: '食谱导入',
					value: 4
				}
			],
			cateringList: [], // 配餐模式列表
			changuiList: [], // 常用食谱列表
			mubanList: [], // 食谱模板
			changguiId: null,
			selectMoshi: null,
			moshiList: [],
			copyMode: [
				{ value: 1, label: '转移' },
				{ value: 2, label: '复制' },
				{ value: 3, label: '替换' }
			],
			dateList: [], // 日期合集
			dateStrList: [
				{ name: '星期一', slot: 'one' },
				{ name: '星期二', slot: 'two' },
				{ name: '星期三', slot: 'three' },
				{ name: '星期四', slot: 'four' },
				{ name: '星期五', slot: 'five' },
				{ name: '星期六', slot: 'six' },
				{ name: '星期日', slot: 'seven' }
			],
			mealList: [],
			data: {},
			drag: false, // 拖拽
			dragType: 1,
			groupItem: { name: 'list' },
			moveId: '',
			moveItem: {
				arrIndex: '',
				index: '',
				key: '',
				value: ''
			},
			wantTomoveItem: {
				index: '',
				key: '',
				aindex: ''
			},
			maskIndex: 1001,
			mealTimeList: [
				{ label: 'breakfast', name: '早餐', type: 0, index: 0 },
				{ label: 'betwwenMealOne', name: '早~午间餐', type: 3, index: 1 },
				{ label: 'lunch', name: '午餐', type: 1, index: 2 },
				{ label: 'betwwenMealTwo', name: '午~晚间餐', type: 4, index: 3 },
				{ label: 'supper', name: '晚餐', type: 2, index: 4 },
				{ label: 'midnightMealOne', name: '夜餐1', type: 5, index: 5 },
				{ label: 'midnightMealTwo', name: '夜餐2', type: 6, index: 6 }
			],
			nums: ['one', 'two', 'three', 'four', 'five', 'six', 'seven'],
			isCheck:0,//判断预生成条件
		}
	},
	computed: {
		personMoney() {
			let total = 0
			if (this.nutritionData.meal_money) {
				for (const key in this.nutritionData.meal_money) {
					if (key != 'avg') {
						total += this.nutritionData.meal_money[key].meal_money
					}
				}
			}
			return (total / 7).toFixed(2)
		},
		totalMoney() {
			let total = 0
			if (this.nutritionData.meal_money) {
				for (const key in this.nutritionData.meal_money) {
					if (key != 'avg') {
						total +=
							this.nutritionData.meal_money[key].meal_money *
							this.nutritionData.jiucanRepastNumer.standardRepastNumer[
								this.nums.indexOf(key)
							]
					}
				}
			}
			return total.toFixed(2)
		}
	},
	mounted() {
		document.oncontextmenu = function(e) {
			return false
			//或者 e.preventDefault()
		}
		this.form = this.$route.query.form
			? this.$cu.deepClone(JSON.parse(this.$route.query.form))
			: {}
		this.isLook = this.form.isLook ? true : false
		this.isChange = this.form.isChange ? true : false
		this.onit()
	},
	beforeDestroy() {
		this.$cu.eventBus.$emit('changeTitle', '')
	},
	// 餐次名称过滤
	filters: {
		mealTimeName(value, mealTimeList) {
			let a = mealTimeList.filter((item) => item.label == value)
			return a.length ? a[0].name : ''
		}
	},
	methods: {
		// 初始化
		onit() {
			// 非新增食谱状态
			if (this.isLook || this.isChange) {
				if (this.isLook) {
					this.$cu.eventBus.$emit('changeTitle', '查看食谱')
				}
				if (this.isChange) {
					this.$cu.eventBus.$emit('changeTitle', '修改食谱')
				}
				this.mealPlanAssessmentApi()
			} else {
				this.mealPlanAssessmentStandardApi()
			}
			// this.form.meal_plan_id = 41;
			this.cateringModeListApi()
			this.getCurrentWeek(this.form.startDate)
			// this.getFoodBookByIdApi().then((deData) => {})
			if (this.form.meal_plan_id) {
				this.getFoodBookByIdApi().then((deData) => {})
			} else {
				if (this.form.make_type == 0) {
					this.getFoodBookByIdApi(0).then((deData) => {})
				} else {
					this.getAptitudeCreateRecipe(0)
				}
			}
		},
		// 选择餐次回调
		chooseMealsOk(arr) {
			this.form.handTypeArr = this.$cu.deepClone(arr)
			this.form.handType = 1
		},
		// 获取就餐人数 --接口
		unitStrengthApi() {
			return new Promise((resolve) => {
				unitStrength({}).then((res) => {
					this.loading = false
					if (res.retCode == 2000 && res.data) {
						this.$set(this.data[7], 'monday', res.data[0].registered)
						this.$set(this.data[7], 'tuesday', res.data[0].registered)
						this.$set(this.data[7], 'wednesday', res.data[0].registered)
						this.$set(this.data[7], 'thursday', res.data[0].registered)
						this.$set(this.data[7], 'friday', res.data[0].registered)
						this.$set(this.data[7], 'saturday', res.data[0].registered)
						this.$set(this.data[7], 'sunday', res.data[0].registered)
						resolve()
					}
					if (res.retCode != 2000) {
						BU
						this.$Message.error(res.retMsg)
					}
				})
			})
		},
		// 只有在创建的时候进入，需要从状态栏拿就餐人数
		getPeople(newVal, peopleList) {
			if (peopleList && peopleList.length) {
				console.log('人数', newVal, peopleList)
				for (let key in newVal) {
					this.nums.forEach((item, index) => {
						newVal[key].dayMeal[item].repastNumber = peopleList[index]
					})
				}
			}
		},
		// 针对后端返回食谱数据做后台筛选
		getReceive(newVal, data, state) {
			console.log(this.form.peopleList)
			this.mealTimeList.forEach((item) => {
				if (state == 1 && item.type < 3)
					for (let key in data) {
						console.log('111', key, item.label)
						if (item.label == key) {
							newVal[key] = data[key]
						}
					}
			})
			console.log('1111', newVal)
		},
		// 智能生成食谱
		getAptitudeCreateRecipe(id, check = 0) {
			this.loading = true
			this.interFaces++
			return new Promise((resolve) => {
				aptitudeCreateRecipe({
					startDate: this.form.begian_time,
					stopDate: this.form.end_time,
					generateExpansionStatus: id == 0 ? 0 : 1,
					checkFlag: check
				}).then((res) => {
					if (res.retCode == 2000) {
						this.loading = false
						let content = ''
						content += `<p style="margin-top:5px">${res.retMsg}</p>`
						// checkFlag判断是否是预生成的代码 ,1为预生成使用完毕重新生成
						if (res.data.checkFlag == 1) {
							this.loading = false
							this.$Modal.warning({
								title: '智能生成食谱',
								content: content,
								width: '600',
								onOk: () => {
									this.getAptitudeCreateRecipe(0, 1)
									this.isCheck = 1 //check传1之后此次保存前就一直为1
								},
								onCancel: () => {
									// 返回上一层
									window.history.back()
								}
							})
							return false
						} else if (res.data.checkFlag == 2) {
							this.getReceive(this.data, res.data, 1)
							this.getPeople(this.data, this.form.peopleList)
							//强制刷新页面数据
							this.$forceUpdate()
							this.interFaces--
							if (this.interFaces == 0) {
								this.loading = false
							}
							this.saveBtn()
						} else {
							this.getReceive(this.data, res.data, 1)
							this.getPeople(this.data, this.form.peopleList)
							//强制刷新页面数据
							this.$forceUpdate()
							this.interFaces--
							console.log(this.interFaces, 'interface')
							if (this.interFaces == 0) {
								this.loading = false
							}
							if (res.data.expansionDishSelectScope == 0 && id == 0) {
								this.$Modal.confirm({
									title: '智能生成食谱成功',
									content: content,
									onOk: () => {
										let check =	this.isCheck ? 1:0
										this.getAptitudeCreateRecipe(1,check)
									},
									onCancel: () => {
										this.saveBtn()
									}
								})
							} else if (res.data.expansionDishSelectScope == 0 && id == 1) {
								this.$Modal.warning({
									title: '智能生成食谱成功',
									content: content,
									width: '600',
									onOk: () => {
										this.saveBtn()
									}
								})
							} else {
								this.$Message.success('智能生成食谱成功')
								this.saveBtn()
							}
						}
					} else {
						// this.$Message.error(res.retMsg ? res.retMsg : '生成食谱失败');
						this.interFaces--
						if (this.interFaces == 0) {
							this.loading = false
						}
						this.$router.go(-1)
					}
				})
			})
		},
		// 智能导入成功
		intellectOk(res) {
			console.log('导入成功', res)
			if (res.retCode == 2000) {
				// this.$Message.success("导入成功!");
				this.$refs['cusUploadNutritionTagModal'].onCancel()
				this.$refs['dishReviewRef'].onShow()
				this.maskIndex = 1000
			}
			// this.$refs["cusUploadNutritionTagModal"].onCancel();
			//   this.$refs["dishReviewRef"].onShow();
		},
		// 智能确认导出成功
		intellectInit(res) {
			for (let key in this.data) {
				console.log(key)
				for (let keyit in this.data[key].dayMeal) {
					if (res.list[key].dayMeal[keyit]) {
						this.data[key].dayMeal[keyit].food =
							res.list[key].dayMeal[keyit].food
					}
				}
			}
		},
		// 智能导入失败
		intellectError(val) {
			console.log('导入失败', val)
			this.$Message.error('导入失败!')
		},
		// 导入
		onImport() {
			this.$refs['cusUploadNutritionTagModal'].show()
		},
		// 导入错误
		onError(data) {
			if (data.retCode == 2888) {
				let content = ''
				data.data.map((it) => {
					content += `<p style="margin-top:5px">${it}</p>`
				})
				this.$Modal.warning({
					title: data.retMsg,
					content: content,
					width: '600',
					okText: '确认'
				})
			}
		},
		// 导入成功
		oninit(res) {
			console.log('返回11111111', this.data)
			for (let key in this.data) {
				console.log(key)
				for (let keyit in this.data[key].dayMeal) {
					if (res.data[key].dayMeal[keyit]) {
						this.data[key].dayMeal[keyit].food =
							res.data[key].dayMeal[keyit].food
					}
				}
			}
			console.log(111111111, res)
		},

		// 获取本周日期组件处理
		getCurrentWeek(date) {
			let nowData = new Date(date) //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
			let currentDay = nowData.getDay()
			if (currentDay == 0) {
				currentDay = 7
			}
			let beforweek = [],
				afterWeek = []
			for (let i = 1; i <= 7; i++) {
				if (currentDay - i >= 0) {
					let DayTime =
						nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000
					beforweek.push(new Date(DayTime).Format('yyyy-MM-dd'))
				} else {
					let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000
					afterWeek.push(new Date(DayTime).Format('yyyy-MM-dd'))
				}
			}
			afterWeek = afterWeek.reverse()
			this.dateList = [...beforweek, ...afterWeek]
		},
		// 改变拖拽模式
		changedragType() {
			if (this.dragType == 1) {
				this.groupItem = { name: 'list' }
			} else if (this.dragType == 2) {
				this.groupItem = { name: 'list', pull: 'clone' }
			} else {
				this.groupItem = { name: 'list' }
			}
		},
		// 开始拖拽
		onMove(e, index, idx) {
			console.log(e)
			this.moveId = e.draggedContext.element.dishCode
			this.moveItem = {
				arrIndex: e.draggedContext.index,
				index,
				key: idx,
				value: this.$cu.deepClone(
					this.data[index].dayMeal[idx].food[e.draggedContext.index]
				)
			}
			console.log(this.moveItem)
		},
		// 拖拽结束事件
		onAdd(e, index, idx) {
			console.log('结束拖拽')
			console.log(e)
			console.log(index)
			console.log(idx)
			var that = this
			var items = this.data[index].dayMeal[idx].food.filter((item) => {
				return item.dishCode == that.moveId
			})
			// 不重复添加
			if (items.length >= 2) {
				this.data[index].dayMeal[idx].food.splice(e.newDraggableIndex, 1)
				this.$Message.warning('已存在相同菜品.')
				//  转移 或 替换模式下，原数组要重新加回去
				if (this.dragType != 2) {
					this.data[this.moveItem.index].dayMeal[this.moveItem.key].food.splice(
						this.moveItem.arrIndex,
						0,
						this.$cu.deepClone(this.moveItem.value)
					)
				}
			} else {
				console.log('dragType--' + this.dragType)
				let Aitem = this.$cu.deepClone(
					this.data[index].dayMeal[idx].food[e.newDraggableIndex + 1]
				)
				console.log(Aitem)
				// 替换菜肴
				if (this.dragType == 3 && Aitem) {
					this.data[index].dayMeal[idx].food.splice(e.newDraggableIndex + 1, 1)
					let olditems = this.data[this.moveItem.index].dayMeal[
						this.moveItem.key
					].food.filter((item) => {
						return item.dishCode == Aitem.dishCode
					})
					console.log(olditems)
					// 如果原数组，已存在被替换菜肴， 那么不添加
					if (!olditems.length) {
						this.data[this.moveItem.index].dayMeal[
							this.moveItem.key
						].food.splice(e.oldIndex, 0, Aitem)
					} else {
						this.$Message.warning('拖拽区替换菜品已存在，将不再添加.')
					}
				}
				// 如果是复制 只需要触发一次接口， 转移和替换要触发两次
				if (this.dragType != 2) {
					if (this.moshiType != 2 && !this.isLook) {
						if (this.form.meal_plan_id == 0) {
							this.saveMealPlanApi()
						} else {
							this.saveMealPlanTimesDishApi(
								this.moveItem.index,
								this.moveItem.key
							)
							this.realTimeCalculateMealPlanDishAssessmentApi(
								this.moveItem.index,
								this.moveItem.key
							)
							this.saveMealPlanTimesDishApi(index, idx)
							this.realTimeCalculateMealPlanDishAssessmentApi(index, idx)
						}
					}
				} else {
					if (this.moshiType != 2 && !this.isLook) {
						if (this.form.meal_plan_id == 0) {
							this.saveMealPlanApi()
						} else {
							this.saveMealPlanTimesDishApi(index, idx)
							this.realTimeCalculateMealPlanDishAssessmentApi(index, idx)
						}
					}
				}
			}
		},
		// 即将进行拖拽
		wantTomove(event, index, key, aindex, item) {
			this.wantTomoveItem = {
				index,
				key,
				aindex
			}
			if (event.button == 2) {
				this.$refs['dishesTags'].form.dishCode = item.dishCode
				this.$refs['dishesTags'].form.dishName = item.dishName
				this.$refs['dishesTags'].show()
			}
			console.log(item)
		},
		// 返回
		backTop() {
			// this.$cu
			//   .dialog({
			//     content: "是否确认返回？确认返回后，您此次操作数据将不会保留",
			//   })
			//   .then(() => {
			//     this.$router.go(-1);
			//   });
			this.$router.go(-1)
		},
		overBtn() {
			this.saveMealPlanApi().then(() => {
				if (this.isChange) {
					this.$router.go(-1)
				} else {
					this.$router.push({
						name: '食谱查询'
					})
				}
			})
		},
		// 保存
		saveBtn() {
			this.isCheck = 0
			this.saveMealPlanApi()
		},
		// 营养分析按钮
		openFenxi() {
			this.$refs['nutritionChart'].show()
		},
		// 添加菜肴
		addBtn(key, key2, selectData) {
			this.$refs['addDishes'].show(0, { key, key2 }, selectData)
		},
		// 修改配餐重量占比
		changeWeightBtn(key, key2, selectData, repastNumber) {
			console.log(key, key2, selectData)
			this.$refs['changeWeight'].show(
				this.form.meal_plan_id,
				{ key, key2 },
				selectData,
				repastNumber,
				this.data,
				this.form.boardId
			)
		},
		// 修改配餐重量占比 -- 成功回调
		changeSettingSuccess() {
			this.getFoodBookByIdApi()
		},
		// 配餐模式下 -- 替换菜肴
		changeDishesBtn(key, key2, arrIndex, dishType) {
			console.log(this.isLook)
			if (this.isLook) return
			this.$refs['changeOneDishes'].show({ key, key2, arrIndex, dishType })
		},
		// 添加菜肴
		onAddBack(form, data) {
			this.$set(
				this.data[form.key].dayMeal[form.key2],
				'food',
				this.$cu.deepClone(data)
			)
			// 手工创建食谱 && 第一次保存
			if (this.moshiType != 2 && !this.isLook) {
				if (this.form.meal_plan_id == 0) {
					this.saveMealPlanApi()
				} else {
					this.saveMealPlanTimesDishApi(form.key, form.key2)
					this.realTimeCalculateMealPlanDishAssessmentApi(form.key, form.key2)
				}
			}
		},
		// 删除菜品
		onDelete(key, key2) {
			this.$set(this.data[key].dayMeal[key2], 'food', [])
			// 手工创建食谱 && 第一次保存
			if (this.moshiType != 2 && !this.isLook) {
				if (this.form.meal_plan_id == 0) {
					this.saveMealPlanApi()
				} else {
					this.saveMealPlanTimesDishApi(key, key2)
					this.realTimeCalculateMealPlanDishAssessmentApi(key, key2)
				}
			}
		},
		// 替换菜肴
		onChangeBack(form, data) {
			console.log(form)
			this.$set(
				this.data[form.key].dayMeal[form.key2].food,
				form.arrIndex,
				data
			)
			if (this.moshiType != 2 && !this.isLook) {
				if (this.form.meal_plan_id == 0) {
					this.saveMealPlanApi()
				} else {
					this.saveMealPlanTimesDishApi(form.key, form.key2)
					this.realTimeCalculateMealPlanDishAssessmentApi(form.key, form.key2)
				}
			}
		},

		// 获取食谱i详情
		getFoodBookByIdApi(id) {
			this.data = []
			this.loading = true
			return new Promise((resolve) => {
				getFoodBookById({
					meal_plan_id: id == 0 ? 0 : this.form.meal_plan_id
				}).then((res) => {
					this.loading = false
					let deData = {}
					if (res.retCode == 0 || res.retCode == 2000) {
						// 保存食谱信息
						if (res.data.meal_plan.meal_plan_id != 0) {
							console.log('-----', res.data)
							this.form = res.data.meal_plan
						}
						this.mealTimeList.forEach((item) => {
							for (const key in res.data) {
								if (item.label == key) {
									console.log(res.data[key])
									deData[key] = res.data[key]
									deData[key].index = item.index
								}
							}
						})
						console.log('抛出值--')
						console.log(deData)
						let that = this
						for (const key in deData) {
							console.log(this.form.make_type, this.form.id)
							// 如果是手工创建，且没有保存过需要把创建时期的就餐人数 和 日期赋值到data中
							if (this.form.make_type == 0 && !this.form.id) {
								console.log(that.form.peopleList)
								for (const key2 in deData[key].dayMeal) {
									let index = that.nums.indexOf(key2)
									// 只有在创建的时候进入，需要从状态栏拿就餐人数  0,2,4分别代表早午晚三餐第一次进入时不需要间餐第一次进入时不需要间餐
									if (
										that.form.peopleList &&
										that.form.peopleList.length &&
										[0, 2, 4].indexOf(deData[key].index) != -1
									) {
										deData[key].dayMeal[key2].repastNumber =
											that.form.peopleList[index]
									}
									deData[key].dayMeal[key2].meal_date = that.dateList[index]
									deData[key].dayMeal[
										key2
									].time_type = this.mealTimeList.filter(
										(item) => item.label == key
									)[0].type
								}
							}
							deData[key].dayMeal = that.nums.reduce((pre, cur) => {
								pre[cur] = deData[key].dayMeal[cur]
								return pre
							}, {})
						}
						this.data = this.objValueSort(deData, 'index')
						this.filterMeal()
					}
					resolve(deData)
				})
			})
		},
		// 获取配餐模式列表 -- 接口
		cateringModeListApi() {
			return new Promise((resolve) => {
				cateringModeList({
					current: 1,
					size: -1
				}).then((res) => {
					if (res.retCode == 2000) {
						this.cateringList = res.data
						// this.form.modeId = res.data[0].modeId;
					}
					resolve()
				})
			})
		},
		// 获取配餐模式详情 -- 接口
		cateringModedtlListApi() {
			this.interFaces++
			this.loading = true
			return new Promise((resolve) => {
				cateringModedtlList({
					current: 1,
					size: -1,
					modeId: this.form.cateringModelId
				}).then((res) => {
					if (res.retCode == 2000) {
						this.interFaces--
						if (this.interFaces == 0) {
							this.loading = false
						}

						let aItem = {}
						this.mealTimeList.forEach((item) => {
							res.data.forEach((it) => {
								it.dishType = it.dishCategory
								if (item.name == it.mealTime) {
									if (!aItem[item.label]) {
										aItem[item.label] = it ? [it] : []
									} else {
										it ? aItem[item.label].push(it) : ''
									}
								}
							})
						})
						console.log(aItem)
						for (const key in aItem) {
							for (const key2 in this.data[key].dayMeal) {
								this.$set(
									this.data[key].dayMeal[key2],
									'food',
									this.$cu.deepClone(aItem[key])
								)
							}
						}
					}
					resolve()
				})
			})
		},
		// 获取常用食谱列表 -- 接口
		queryMealPlanApi() {
			return new Promise((resolve) => {
				queryMealPlan({
					current: 1,
					size: -1,
					isCommonly: 1
				}).then((res) => {
					if (res.retCode == 2000) {
						this.changuiList = res.data.records
					}
					resolve()
				})
			})
		},
		// 获取食谱模板列表 -- 接口
		getMouldApi() {
			return new Promise((resolve) => {
				getMould({
					current: 1,
					size: -1,
					mouldType: 'dining'
				}).then((res) => {
					if (res.retCode == 2000) {
						this.mubanList = res.data
					}
					resolve()
				})
			})
		},
		// 保存食谱（第一次保存， 传全部） -- 接口
		saveMealPlanApi() {
			this.interFaces++
			this.loading = true
			let aitem = this.$cu.deepClone(this.data)
			// let aDeyMeal = this.$cu.deepClone(this.data.breakfast.dayMeal);
			// for (const key in aDeyMeal) {
			//     aDeyMeal[key].food = [];
			//     aDeyMeal[key].time_type = 0;
			// }
			// this.mealTimeList.forEach(item => {
			//     if(!aitem[item.label]) {
			//         aitem[item.label] = {dayMeal: aDeyMeal}
			//     }
			// });
			let betwwenMealOne = this.$cu.deepClone(this.data.lunch)
			for (let key in betwwenMealOne.dayMeal) {
				betwwenMealOne.dayMeal[key].repastNumber = 0
				betwwenMealOne.dayMeal[key].food = []
			}
			// 给为加餐段添加间餐
			this.mealTimeList.forEach((item, index) => {
				if (item.label in aitem) {
					aitem[item.label].index = index
				} else {
					console.log(item.label, index)
					aitem[item.label] = this.$cu.deepClone(betwwenMealOne)
					console.log('-----', aitem[item.label])
					for (let key in aitem[item.label].dayMeal) {
						aitem[item.label].dayMeal[key].time_type = item.type
					}
					aitem[item.label].index = index
				}
			})
			aitem.meal_plan = {
				begian_time: this.form.startDate,
				end_time: this.form.stopDate,
				name: this.form.name,
				make_type: this.form.make_type,
				cateringModelId:
					this.form.cateringModelId || this.cateringList[0].modeId,
				meal_plan_id: this.form.meal_plan_id,
				boardId: this.form.boardId,
				stallDescr: this.form.stallDescr,
				stallId: this.form.stallId
			}
			return new Promise((resolve) => {
				saveMealPlan(aitem).then((res) => {
					this.interFaces--
					if (this.interFaces == 0) {
						this.loading = false
					}

					if (res.retCode == 2000) {
						this.$Message.success('食谱保存成功.')
						this.form.meal_plan_id = res.data.meal
						this.getFoodBookByIdApi()
						this.mealPlanAssessmentApi()
						resolve()
					} else this.$Message.error(res.retMsg)
				})
			})
		},
		// 保存食谱（第二次 或 以上次数保存，保存、某一餐） -- 接口
		saveMealPlanTimesDishApi(key, key2) {
			console.log('执行部分保存---')
			this.interFaces++
			this.loading = true
			let aitem = {}
			aitem.meal_plan = {
				cateringModelId:
					this.form.cateringModelId || this.cateringList[0].modeId,
				meal_plan_id: this.form.meal_plan_id
			}
			aitem.mealTimes = this.mealTimeList.filter(
				(item) => item.label == key
			)[0].type
			aitem.weekTimes = key2
			aitem.MealTimesDish = {}
			aitem.MealTimesDish.dayMeal = this.$cu.deepClone(this.data[key].dayMeal)
			return new Promise((resolve) => {
				saveMealPlanTimesDish(aitem).then((res) => {
					this.interFaces--
					if (this.interFaces == 0) {
						this.loading = false
					}

					if (res.retCode == 2000) {
						// this.$Message.success('食谱修改成功.')
						this.form.meal_plan_id = res.data.result
						this.getFoodBookByIdApi()
						resolve()
					} else this.$Message.error(res.retMsg)
				})
			})
		},
		// 顶部模式切换 （食谱模板...等）
		changeMoshi(value) {
			console.log(value)
			if (value == 1) {
				// 先把模板制空
				this.getFoodBookByIdApi()
				this.queryMealPlanApi()
			} else {
				this.changguiId = null
			}
			if (value == 2) {
				this.form.cateringModelId = this.cateringList[0].modeId
				this.cateringModedtlListApi()
			} else {
				this.form.cateringModelId = null
			}
			if (value == 3) {
				this.getMouldApi()
			}
		},
		// 常用食谱切换
		changeChangui(value) {
			if (value) {
				this.getChangguiDel(value).then((res) => {
					this.$refs['chooseCoverData'].show(this.data, res)
				})
			}
		},
		// 配餐模式切换
		changePeican(value) {
			this.cateringModedtlListApi()
		},
		// 食谱模板切换 (固定只有三餐)
		changeMuban(value) {
			let a = this.mubanList.filter((item) => item.mouldId == value)
			console.log(a)
			let aMealTimeList = [
				{ label: 'breakfast', name: '早餐', type: 0, name: 'breakfast' },
				{ label: 'lunch', name: '午餐', type: 1, name: 'lunch' },
				{ label: 'supper', name: '晚餐', type: 2, name: 'dinner' }
			]
			let changeData = {}
			aMealTimeList.forEach((item) => {
				let sItem = a[0][item.name]
				changeData[item.label] = {}
				changeData[item.label].dayMeal = {}
				sItem.forEach((it) => {
					this.nums.forEach((num, nidx) => {
						let addIt = this.$cu.deepClone(it[num])
						if (!changeData[item.label].dayMeal[num]) {
							changeData[item.label].dayMeal[num] = {
								begintime: null,
								choose_dish: 0,
								endtime: null,
								food: addIt ? [addIt] : [],
								meal_date: this.dateList[nidx],
								meal_plandtl_id: this.form.meal_plan_id,
								repastNumber: this.form.peopleList[nidx],
								time_id: 0,
								time_type: item.type,
								week: num
							}
						} else {
							addIt ? changeData[item.label].dayMeal[num].food.push(addIt) : ''
						}
					})
				})
			})
			console.log(changeData)
			this.data = changeData
		},
		// 获取食谱评估空模板 -- 接口
		mealPlanAssessmentStandardApi() {
			return new Promise((resolve) => {
				mealPlanAssessmentStandard({}).then((res) => {
					if (res.retCode == 2000) {
						this.nutritionData = res.data
						resolve()
					} else this.$Message.error(res.retMsg)
				})
			})
		},
		// 第一次保存食谱评估 -- 接口
		mealPlanAssessmentApi() {
			this.loading = true
			this.interFaces++
			return new Promise((resolve) => {
				mealPlanAssessment({
					mealPlanId: this.form.meal_plan_id
				}).then((res) => {
					this.interFaces--
					if (this.interFaces == 0) {
						this.loading = false
					}

					if (res.retCode == 2000) {
						if (!this.isLook && !this.isChange)
							this.$Message.success('食谱营养评估成功.')
						this.nutritionData = res.data
						resolve()
					} else this.$Message.error(res.retMsg)
				})
			})
		},
		// 实时计算食谱菜肴评估-按天为单位 -- 接口
		realTimeCalculateMealPlanDishAssessmentApi(key, key2) {
			// console.log('实时计算食谱菜肴评估--')
			// console.log(key, key2)
			// console.log(this.data)
			let aItem = {}
			// let aArr = this.data[key].dayMeal[key2].food.map(item => item.dishCode);
			// aItem[key] = aArr;
			this.mealTimeList.forEach((item, index) => {
				// if(aItem[item.label] == undefined) {
				//     aItem[item.label] = []
				// } else {
				//     aItem[item.label] = this.data[key].dayMeal[key2].food.map(item => item.dishCode);
				// }
				if (this.data[item.label] == undefined) {
					aItem[item.label] = []
				} else {
					aItem[item.label] = this.data[item.label].dayMeal[key2].food.map(
						(item) => item.dishCode
					)
				}
			})
			aItem.week = key2
			aItem.mealPlanId = this.form.meal_plan_id
			aItem.boardId = this.form.boardId
			aItem.mealRepastNumber = []
			for (const keydata in this.data) {
				aItem.mealRepastNumber.push({
					weekTime: key2,
					mealTime: this.data[keydata].dayMeal[key2].time_type,
					repastNumber: this.data[keydata].dayMeal[key2].repastNumber,
					repurDate: this.data[keydata].dayMeal[key2].meal_date
				})
			}
			console.log(aItem)
			return new Promise((resolve) => {
				realTimeCalculateMealPlanDishAssessment(aItem).then((res) => {
					if (res.retCode == 2000) {
						// this.$Message.success('食谱营养评估成功.')
						// this.mealPlanAssessmentApi();
						this.$set(
							this.nutritionData.meal_money,
							key2,
							res.data.meal_money[key2]
						)
						this.$set(
							this.nutritionData.nutritional_analysis,
							key2,
							res.data.nutritional_analysis[key2]
						)
						this.$set(
							this.nutritionData.quantifyAnalysis,
							key2,
							res.data.quantifyAnalysis[key2]
						)
						this.$set(this.nutritionData, 'avgMoney', res.data.avgMoney)
						this.$set(
							this.nutritionData,
							'sumTotalAmount',
							res.data.sumTotalAmount
						)
						resolve()
					} else this.$Message.error(res.retMsg)
				})
			})
		},
		// 显示营养详情弹窗
		showNurBtn() {
			this.showNutrition = true
			this.$refs['nutritionModal'].show()
		},
		closeShowNutrition() {
			this.showNutrition = false
			this.$refs['nutritionModal'].showValue = false
		},
		// 获取常用食谱数据详情
		getChangguiDel(id) {
			return new Promise((resolve) => {
				getFoodBookById({
					meal_plan_id: id
				}).then((res) => {
					let deData = []
					if (res.retCode == 0 || res.retCode == 2000) {
						deData = res.data
					}
					resolve(deData)
				})
			})
		},
		coverSuccess(arr) {
			this.data = arr
			this.saveMealPlanApi()
		},
		// 对像排序
		objValueSort(obj, key, sortType) {
			// 排序的函数
			// 1.根据数组中的对象的“xxx”，得到排序后的key，return y-x 表示降序  x-y 表示升序
			const newkey = Object.keys(obj).sort((a, b) => {
				let x = Number(obj[a][key])
				let y = Number(obj[b][key])
				if (sortType) {
					return y - x
				} else {
					return x - y
				}
			})
			// 2.用排序后的key构建新的对象数组
			const newObj = {} // 创建一个新的对象，用于存放排好序的键值对
			for (let i = 0; i < newkey.length; i++) {
				// 遍历newkey数组
				newObj[newkey[i]] = obj[newkey[i]] // 向新创建的对象中按照排好的顺序依次增加键值对
				newObj[newkey[i]].index = i + 1
			}
			return newObj // 返回排好序的新对象
		},
		// 修改就餐人数或设置就餐间餐
		changeNumBtn(val) {
			if (val == 1 && !this.isChange) {
				console.log('食谱数据', this.data)
				let betwwenMealOne = this.$cu.deepClone(this.data.lunch)
				for (let key in betwwenMealOne.dayMeal) {
					betwwenMealOne.dayMeal[key].repastNumber = 0
					betwwenMealOne.dayMeal[key].food = []
				}
				// 给为加餐段添加间餐
				this.mealTimeList.forEach((item, index) => {
					if (item.label in this.data) {
						this.data[item.label].index = index
					} else {
						console.log(item.label, index)
						this.data[item.label] = this.$cu.deepClone(betwwenMealOne)
						console.log('-----', this.data[item.label])
						for (let key in this.data[item.label].dayMeal) {
							this.data[item.label].dayMeal[key].time_type = item.type
						}

						this.data[item.label].index = index
					}
				})
				this.data = this.objValueSort(this.data, 'index')
				// 过滤一周都没有人数的简餐段

				console.log('---', this.data)
				console.log(typeof this.data)
				this.$refs['changeNum'].show(this.data)
			} else {
				this.$refs['changeNum'].show(this.data)
			}
			this.filterMeal()
		},
		// 过滤餐谱数组
		filterMeal() {
			// isChange 是否为修改状态
			if (!this.isChange) {
				console.log('增加间餐', this.data)
				for (let key in this.data) {
					let i = true
					// console.log(,'测试');
					
					if(['breakfast','lunch','supper'].includes(key)) {
						return
					}
					console.log(this.data[key].dayMeal)
					for (let keym in this.data[key].dayMeal) {
						if (this.data[key].dayMeal[keym].repastNumber != 0) {
							i = false
						}
					}
					if (i) {
						console.log(key)
						Reflect.deleteProperty(this.data, key)
						console.log('11', this.data)
					}
				}
			}

			this.$forceUpdate()
		},
		// 改变人数传回整个食谱数据
		changerepastNumber(newData) {
			this.data = this.$cu.deepClone(newData)
			// 筛选整个周没有人数的间餐
			this.filterMeal()
			this.$forceUpdate()
		},
		// 导出
		onExport(type) {
			this.exportExcelApi(type)
		},
		// 导出Api
		exportExcelApi(type) {
			this.$cu.showLoading()
			let fnc = null
			if (type == 1) {
				fnc = downloadMealFoodTable
			} else if (type == 2) {
				// fnc = getFoodBookStatement;
			} else {
				fnc = mealAssessmentReportExcel
			}
			if (type != 2) {
				return new Promise((resolve) => {
					fnc({
						mealPlanId: this.form.meal_plan_id
					}).then((res) => {
						this.$cu.hideLoading(1)
						let msg = ''
						let downloadName = ''
						if (type == 1) {
							msg = '食谱下料清单导出成功.'
							downloadName = '食谱下料清单'
						} else if (type == 2) {
							msg = '食谱公布表导出成功.'
							downloadName = '食谱公布表'
						} else {
							msg = '食谱评估报告导出成功.'
							downloadName = '食谱评估报告'
						}
						this.$Message.success(msg)
						let blob = new Blob([res], { type: `application/vnd.ms-excel` })
						let downloadElement = document.createElement('a')
						let href = window.URL.createObjectURL(blob)
						downloadElement.href = href
						downloadElement.download = downloadName
						document.body.appendChild(downloadElement)
						downloadElement.click()
						document.body.removeChild(downloadElement)
						window.URL.revokeObjectURL(href)
						resolve()
					})
				})
			} else {
				this.$cu.hideLoading(1)
				window.location.href =
					getFoodBookStatement + `&mealPlanId=${this.form.meal_plan_id}`
			}
		}
	}
}
</script>

<style lang="less" scoped>
/*里面的代码可以根据自己需求去进行更改*/
/* 设置滚动条的样式 */
::-webkit-scrollbar {
	width: 4px;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
	border-radius: 10px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
	border-radius: 10px;
	background: rgba(0, 0, 0, 0.1);
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}

::-webkit-scrollbar-thumb:window-inactive {
	background: rgba(255, 255, 255, 0.4);
}

.contentBox {
	height: 100%;
	border-radius: 2px;
}

.operBox {
	position: fixed;
	bottom: 0;
	right: 0;
	height: 88px;
	display: flex;
	flex-direction: row-reverse;
	// width: 100%;
	background: #ffffff;
	align-items: center;
	padding: 0 40px;
	box-shadow: 0px -1px 6px 0px rgba(0, 0, 0, 0.12),
		0px -1px 2px -2px rgba(0, 0, 0, 0.16);
}

.content {
	background: #ffffff;
	border-radius: 4px;
	border: 0px solid #b9b9b9;

	&-top {
		&-title {
			height: 80px;
			border-bottom: 1px solid rgba(0, 0, 0, 0.06);
			padding: 0 24px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			&-left {
				display: flex;
				align-items: center;

				&-name {
					display: flex;
					align-items: center;
				}

				div {
					line-height: 40px;
					font-size: 16px;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;

					span {
						margin-right: 10px;
					}
				}
			}

			&-right {
				line-height: 40px;
				font-size: 16px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;

				span {
					margin-right: 10px;
				}
			}
		}

		&-table {
			overflow: hidden;
			overflow-y: auto;
			// background-color: pink;
			padding: 24px;
		}
	}

	&-bottom {
		height: 72px;
		background: #ffffff;
		box-shadow: 0px 5px 12px 4px rgba(0, 0, 0, 0.09),
			0px 1px 6px 0px rgba(0, 0, 0, 0.12), 0px 1px 2px -2px rgba(0, 0, 0, 0.16);
		border-radius: 4px;
		border: 0px solid #b9b9b9;

		&-right {
			display: flex;
			align-items: center;
		}
	}
}

.addtable {
	&-title {
		display: flex;
		border-left: 3px solid #33a5fe;
		border-top: 1px solid #cccccc;
		border-bottom: 1px solid #cccccc;

		&-title {
			width: 160px;
			height: 50px;
			background: #33a5fe;
			border-right: 1px solid #cccccc;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 12px;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #ffffff;
		}

		&-item {
			flex: 1;
			height: 50px;
			background: #33a5fe;
			border-right: 1px solid #cccccc;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 12px;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #ffffff;
		}
	}

	&-body {
		overflow: hidden;
		overflow-y: auto;

		&-hang {
			display: flex;
			min-height: 33.3333%;
			border-bottom: 1px solid #cccccc;

			&-title {
				background: #fff;
				border-right: 1px solid #cccccc;
				width: 160px;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 12px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}

			&-content {
				flex: 1;
				border-right: 1px solid #cccccc;
			}
		}
	}
}

.hang1 {
	border-left: 3px solid #33c383;
	background: rgba(51, 195, 131, 0.1);
}

.hang2 {
	border-left: 3px solid #ffc432;
	background: rgba(255, 234, 153, 0.1);
}

.hang0 {
	border-left: 3px solid #49afff;
	background: rgba(73, 175, 255, 0.1);
}

.mr_16 {
	margin-right: 16px;
}

.draggableItem {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 12px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #333333;
	min-height: 25px;
	// line-height: 25px;
	border-bottom: 1px solid #cccccc;
	margin-bottom: 10px;
	cursor: pointer;
	padding-bottom: 3px;
}

.dragClass {
	background: red !important;
	color: #ffffff !important;
}

.btnBox {
	display: flex;
	align-items: center;
	justify-content: center;

	div {
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;

		span {
			size: 12px;
		}
	}

	padding: 10px 0;
}

.peopleNum {
	text-align: center;
	font-size: 12px;
}

// loading样式
.demo-spin-col .circular {
	width: 25px;
	height: 25px;
}

.demo-spin-icon-load {
	animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
	from {
		transform: rotate(0deg);
	}

	50% {
		transform: rotate(180deg);
	}

	to {
		transform: rotate(360deg);
	}
}

.demo-spin-col {
	height: 100px;
	position: relative;
	border: 1px solid #eee;
}

.draw {
	&-section {
		display: flex;
		align-items: center;
		justify-content: space-around;

		&-item {
			background: white;
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 220px;
			cursor: pointer;
			width: 170px;

			&-title {
				text-align: center;
				margin-top: 10px;
				color: rgba(51, 51, 51, 1);
			}

			&-label {
				text-align: center;
				color: rgba(153, 153, 153, 1);
			}
		}
	}
}
</style>
